package com.woniuxy.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import com.woniuxy.gateway.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 鉴权
 */
@Slf4j
@Order(10) //值越大优先级越小
@Component
public class AuthFilter implements GlobalFilter {
    //    private RedisTemplate<String,Object> redisTemplate;
    //    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //权限的模型：ACL，RBAC(用)

        //前提：登录以后会把该用户的权限（资源：path）放到redis中，hash(key:userId,filer:path,value:数据)

        //鉴权：当前请求的用户ID，当前请求的path，拿用户ID和path到redis中取值，有：放行  无：返回
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
        String json = JWTUtil.parseToken(token).getPayload("user").toString();
        UserDto userDto = JSONObject.parseObject(json, UserDto.class);

        //当前请求的用户ID
        String userId = userDto.getId().toString();

        //当前请求的path
        String path = request.getPath().toString();

        //拿用户ID和path到redis中取值，存在就放行
        return redisTemplate.opsForHash().hasKey(userId,path).flatMap(b->{
           if(b){
               //放行
               return chain.filter(exchange);
           }else {
               log.error("login is error");
               ServerHttpResponse response = exchange.getResponse();
               response.setStatusCode(HttpStatus.UNAUTHORIZED);
               String jsonStr = "{\"status\":\"403\", \"msg\":\"鉴权非法\"}";
               byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
               DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
               return exchange.getResponse().writeWith(Flux.just(buffer));

           }
        });


    }
}
